import auth.User
import auth.Role
import javax.servlet.http.HttpServletRequest
import org.apache.commons.codec.digest.DigestUtils

class BootStrap {

    def init = { servletContext ->
    
        HttpServletRequest.metaClass.isXhr = { ->
            'XMLHttpRequest' == delegate.getHeader('X-Requested-With')
        }

        def admin = User.findByEmail("guillaume.alleon@gmail.com")
        if (!admin) {
            def password = System.getProperty("initial.admin.password")
            if (!password) {
                throw new Exception("""
During the first run you must specify a password to be used for the admin account. For example:

grails -Dinitial.admin.password=changeme run-app""")
            } else {
                def user = new User(email:"guillaume.alleon@gmail.com", password:DigestUtils.shaHex(password))
                println "user ${user.email} has been created with password ${user.password}"
                assert user.email
                assert user.addToRoles(name:Role.ADMINISTRATOR).addToRoles(name:Role.USER).save(flush:true)
            }
        } else {
            if (!admin.roles) {
                admin.addToRoles(name:Role.ADMINISTRATOR).addToRoles(name:Role.USER).save(flush:true)
            }
        }

        Cms cms = new Cms(title: 'Acoustic Content Management Service', cmsid: 'acoustic')
        cms.save()

        AbstractWorkflow awf1 = new AbstractWorkflow(parameterName:["inputImage", "outputImage"], parameterClass:[java.io.File.class, java.io.File.class], parameterType:["In", "Out"], description:"Swirl Component");
        awf1.save();
        AbstractWorkflow awf2 = new AbstractWorkflow(parameterName:["inputImage", "outputImage"], parameterClass:[java.io.File.class, java.io.File.class], parameterType:["In", "Out"], description:"Merge Component");
        awf2.save();
        AbstractWorkflow awf3 = new AbstractWorkflow(parameterName:["inputImage1", "inputImage2", "outputImage"], parameterClass:[java.io.File.class, java.io.File.class, java.io.File.class], parameterType:["In", "In", "Out"], description:"Composite Component");
        awf3.save();
    }

    def destroy = {
    }
} 
